package com.xjm.service.serviceImpl;

import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import com.xjm.constant.AppConst;
import com.xjm.utils.RedisUtil;
import com.xjm.service.CodeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class CodeServiceImpl implements CodeService {

    private final RedisUtil redisUtil;


    /**
     * 使用简单方式获取验证码 uuid生成
     * @return JSON
     */
    @Override
    public JSON getSimpleCode() {
        String uuid = UUID.fastUUID().toString();
        String key = AppConst.CODE_KEY + uuid;
        String value = UUID.fastUUID().toString().substring(0,4);
        redisUtil.set(key, value, 60 * 5);
        JSON json = new JSONObject();
        json.putByPath("sign", uuid);
        json.putByPath("code", value);
        return json;
    }

    /**
     * 检验验证码
     * @param key 存储的key
      * @param code 验证码
     * @return 检验结果
     */
    @Override
    public Boolean checkCode(String key, String code) {
        key = AppConst.CODE_KEY  + key;
        if (redisUtil.hasKey(key)) {
            String value = (String) redisUtil.get(key);
            if (value.equals(code)) {
                redisUtil.delete(key);
                return true;
            }
        }
        return false;
    }
}
